# -*- coding: utf-8 -*-
"""
python 屏幕录制改进版，无opencv黑框显示！
@zhou 2020/1/29_
"""
from time import sleep

from PIL import ImageGrab
import numpy as np
import cv2
import datetime
from pynput import keyboard
import threading



video_flag = False  # 停止标志位
def video_record():
    # video_flag = video_flag

    # global flag  # 停止标志位
    # flag = False
    """
    屏幕录制！
    :return:
    """
    name = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')  # 当前的时间
    # vid = cv2.VideoCapture('./2022-06-13 15-33-12.avi')
    # video_width = int(vid.get(3))
    # video_height = int(vid.get(4))
    p = ImageGrab.grab()  # 获得当前屏幕
    a, b = p.size  # 获得当前屏幕的大小
    print((a,b))
    fourcc = cv2.VideoWriter_fourcc(*'XVID')  # 编码格式
    video = cv2.VideoWriter('%s.mp4v' % name, fourcc, 16, (a, b))  # 输出文件命名为test.mp4,帧率为16，可以自己设置
    while True:
        im = ImageGrab.grab()
        imm = cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)  # 转为opencv的BGR格式
        video.write(imm)
        if video_flag:
            print("录制结束！")
            break
    video.release()


def on_press():
    """
    键盘监听事件！！！
    :param key:
    :return:
    """
    # print(key)
    global video_flag
    # if key == keyboard.Key.esc:
    video_flag = True
    print("stop monitor！")
    return False  # 返回False，键盘监听结束！


# flag = False
# th = threading.Thread(target=video_record,args=)
# th.start()
# sleep(5)
# on_press()

